from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from datetime import datetime
from models.request_log import RequestLog
from dao.postgresql_connect import SessionLocal
from schemas.generated.logs import *
from typing import List

admin_router = APIRouter()

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@admin_router.get("/admin/logs", response_model=List[LogResponse])
async def get_logs(
    db: Session = Depends(get_db),
    start_time: Optional[datetime] = None,
    end_time: Optional[datetime] = None,
    route: Optional[str] = None,
    status_code: Optional[int] = None,
    ip_address: Optional[str] = None,
    user_id: Optional[int] = None,
    limit: int = Query(default=100, le=1000),
    offset: int = 0
):
    """
    获取系统请求日志
    - start_time: 开始时间
    - end_time: 结束时间
    - route: 请求路径
    - status_code: 响应状态码
    - ip_address: IP地址
    - user_id: 用户ID
    - limit: 返回记录数量限制
    - offset: 分页偏移量
    """
    query = db.query(RequestLog)
    
    if start_time:
        query = query.filter(RequestLog.timestamp >= start_time)
    if end_time:
        query = query.filter(RequestLog.timestamp <= end_time)
    if route:
        query = query.filter(RequestLog.route.like(f"%{route}%"))
    if status_code:
        query = query.filter(RequestLog.response_status == status_code)
    if ip_address:
        query = query.filter(RequestLog.ip_address == ip_address)
    if user_id:
        query = query.filter(RequestLog.user_id == user_id)
    
    # 按时间倒序排序
    query = query.order_by(RequestLog.timestamp.desc())
    
    return query.offset(offset).limit(limit).all() 